
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "../iface/debug.h"
#include "../utils/BaseConvert.h"
#include "../utils/StringUtils.h"
#include "RSAPublicKey.h"

RSAPublicKey::RSAPublicKey()
{
   key = NULL;
   keyname = NULL;
}

RSAPublicKey::RSAPublicKey(const char *name)
{
   key = NULL;
   keyname = NULL;
   SetKeyName(name);
}

// Construct a duplicate of the public key
RSAPublicKey::RSAPublicKey(const RSAPublicKey &other)
{
   key = RSA_new();
   if (key == NULL)
   {
      errprint("RSA_new failed");
      return;
   }
   if (CopyRSASSLPublicKey(key, other.key))
   {
      errprint("RSA_new failed");
      return;
   }
   keyname = NULL;
   SetKeyName(other.keyname);
}

// Construct from PEM format
RSAPublicKey::RSAPublicKey(const char *pemtext, const char *name)
{
   
}

// Construct from OpenSSL format
RSAPublicKey::RSAPublicKey(RSA *pubkey, const char *name)
{
   key = RSA_new();
   if (key == NULL)
   {
      errprint("RSA_new failed");
      return;
   }
   int errval = CopyRSASSLPublicKey(key, pubkey);
   keyname = NULL;
   SetKeyName(name);
}

RSAPublicKey::~RSAPublicKey()
{
   if (key) RSA_free(key);
   key = NULL;
   if (keyname) free((void *)keyname);
   keyname = NULL;
}

// Get context
int RSAPublicKey::GetCryptlibContext(CRYPT_CONTEXT *keyContext)
{
   int status;
   CRYPT_PKCINFO_RSA *rsaKey = (CRYPT_PKCINFO_RSA *)malloc(sizeof(CRYPT_PKCINFO_RSA));
   if (GetCryptlibKeyComponents(rsaKey) != 0)
   {
      free(rsaKey);
      return -1;
   }
   int magictriescntxt = 0;
   do
   {
      status = cryptCreateContext(keyContext, CRYPT_UNUSED, CRYPT_ALGO_RSA);
      if (status == CRYPT_ERROR_TIMEOUT) apr_sleep(rand() % CRYPT_MAX_TIMESLEEP);
      magictriescntxt++;
   } while ((status == CRYPT_ERROR_TIMEOUT) && (magictriescntxt < CRYPT_MAX_RETRIES));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   status = cryptSetAttributeString(*keyContext, CRYPT_CTXINFO_LABEL, keyname, strlen(keyname));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   status = cryptSetAttributeString(*keyContext, CRYPT_CTXINFO_KEY_COMPONENTS, rsaKey, sizeof(CRYPT_PKCINFO_RSA));
   fCryptCheckError(status);
   if (status != CRYPT_OK) goto failover;
   cryptDestroyComponents(rsaKey);
   free(rsaKey);
   return 0;
failover:
   cryptDestroyComponents(rsaKey);
   free(rsaKey);
   return -1;
}

// Get context
int RSAPublicKey::GetCryptlibEncryptionContext(CRYPT_CONTEXT *keyContext)
{
   return GetCryptlibContext(keyContext);
}

// Get context
int RSAPublicKey::GetCryptlibCheckingContext(CRYPT_CONTEXT *keyContext)
{
   return GetCryptlibContext(keyContext);
}

// Get key components
int RSAPublicKey::GetCryptlibKeyComponents(CRYPT_PKCINFO_RSA *rsaKey)
{
   unsigned char *buffera[2];
   cryptInitComponents(rsaKey, CRYPT_KEYTYPE_PUBLIC);
   buffera[0] = (unsigned char *)malloc(BN_num_bytes(key->n));
   if (!(buffera[0])) { errprint("could not allocate buffer for key->n."); return -1; }
   buffera[1] = (unsigned char *)malloc(BN_num_bytes(key->e));
   if (!(buffera[1])) { errprint("could not allocate buffer for key->e."); return -1; }
   BN_bn2bin(key->n, buffera[0]);
   BN_bn2bin(key->e, buffera[1]);
   cryptSetComponent(rsaKey->n, buffera[0], BN_num_bits(key->n));
   cryptSetComponent(rsaKey->e, buffera[1], BN_num_bits(key->e));
   for (int i = 0; i < 2; i++) free(buffera[i]);
   return 0;
}

// Get new OpenSSL RSA object
int RSAPublicKey::GetSSLKeyComponents(RSA **pubkey)
{
   *pubkey = RSA_new();
   if ((*pubkey) == NULL)
   {
      errprint("RSA_new failed");
      return -1;
   }
   return CopyRSASSLPublicKey(*pubkey, key);
}

// Get PEM data
int RSAPublicKey::GetPEMKeyData(char **pemtext)
{
   char *data;
   int damt;
   char *dbuf = NULL;
   int retval = 0;
   EVP_PKEY *epkey = EVP_PKEY_new();
   EVP_PKEY_set1_RSA(epkey, key);
   BIO *bo = BIO_new(BIO_s_mem());
   if (!PEM_write_bio_PUBKEY(bo, epkey))
   {
      retval = 1;
      errprint("could not export public key");
      fSSLCheckError();
      goto bioshutdown;
   }
   fSSLCheckError();
   damt = BIO_get_mem_data(bo, &data);
   *pemtext = (char *)malloc(sizeof(char)*(damt+1));
   memcpy(*pemtext, data, sizeof(char)*(damt+1));
   (*pemtext)[damt] = '\0';
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   EVP_PKEY_free(epkey);
   return retval;
}

// Get OpenSSH binary blob
int RSAPublicKey::GetSSHKeyBlob(char **blob, int *reallength)
{
   const unsigned char keyheader[11] = { 0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2D, 0x72, 0x73, 0x61 };
   unsigned char *n_buffer = NULL;
   unsigned char *e_buffer = NULL;
   int n_len = BN_num_bytes(key->n);
   int e_len = BN_num_bytes(key->e);
   n_buffer = (unsigned char *)malloc(n_len);
   if (!n_buffer) { errprint("Could not allocate buffer for pub->n."); return -1; }
   e_buffer = (unsigned char *)malloc(e_len);
   if (!e_buffer) { errprint("Could not allocate buffer for pub->e."); return -1; }
   BN_bn2bin(key->n, n_buffer);
   BN_bn2bin(key->e, e_buffer);
   int enclen = 4 + 7 + 4 + ((e_buffer[0] & 0x80) == 0x80) + e_len + 4 + ((n_buffer[0] & 0x80) == 0x80) + n_len;
   char *encode = (char *)malloc(sizeof(char)*enclen);
   memcpy(encode, keyheader, sizeof(char)*11);
   int real_len, data_start, toffset;
   toffset = 11;
   real_len = e_len + ((e_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((e_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), e_buffer, sizeof(char)*e_len);
   toffset += (real_len + 4);
   real_len = n_len + ((n_buffer[0] & 0x80) == 0x80);
   data_start = 4 + ((n_buffer[0] & 0x80) == 0x80);
   memset(&(encode[toffset]), 0, sizeof(char)*(real_len + 4));
   encode[toffset + 0] = (unsigned char)(real_len >> 24);
   encode[toffset + 1] = (unsigned char)(real_len >> 16);
   encode[toffset + 2] = (unsigned char)(real_len >>  8);
   encode[toffset + 3] = (unsigned char)(real_len);
   memcpy(&(encode[toffset + data_start]), n_buffer, sizeof(char)*n_len);
   free(n_buffer); free(e_buffer);
   if (reallength) *reallength = enclen;
   if (blob) *blob = encode;
   return 0;
}

// Get OpenSSH text with key label
int RSAPublicKey::GetSSHKeyBlob(char **textblob, const char *keylabel)
{
   int enclen = 0;
   char *encode;
   if (GetSSHKeyBlob(&encode, &enclen) != 0) return -1;
   char *base64string = BaseConvert::ConvertBytesToBase64(encode, enclen);
   free(encode);
   char *finalstring = StringUtils::varprintf("ssh-rsa %s %s", base64string, keylabel);
   free(base64string);
   if (textblob) *textblob = finalstring;
   return 0;
}

// Compare public key to public key
int RSAPublicKey::CompareKeyEqual(PublicKey *pubkey)
{
   if (pubkey == NULL)
   {
      errprint("comparing against NULL key");
      return 0;
   }
   switch (pubkey->GetKeyType())
   {
      case KEY_TYPE_PUBLIC_RSA:
      {
         RSA *rsaKeyOther = NULL;
         ((RSAPublicKey *)pubkey)->GetSSLKeyComponents(&rsaKeyOther);
         EVP_PKEY *evp1 = EVP_PKEY_new();
         EVP_PKEY *evp2 = EVP_PKEY_new();
         EVP_PKEY_set1_RSA(evp1, key);
         EVP_PKEY_set1_RSA(evp2, rsaKeyOther);
         int retval = EVP_PKEY_cmp(evp1, evp2);
         EVP_PKEY_free(evp1);
         EVP_PKEY_free(evp2);
         RSA_free(rsaKeyOther);
         fSSLCheckError();
         switch (retval)
         {
            case -2:
               errprint("key compare operation not supported (EVP_PKEY_cmp())");
               break;
            case -1:
               errprint("tried to compare different key types (EVP_PKEY_cmp())");
               return 0;
            case 0:
               return 0;
            case 1:
               return 1;
         }
         return 0;
      }
      default:
      {
         return 0;
         break;
      }
   }
}

int RSAPublicKey::CopyRSASSLPublicKey(RSA *dst, RSA *src)
{
   if (dst == NULL) { errprint("NULL public key destination"); return -1; }
   if (src == NULL) { errprint("NULL public key source"); return -1; }
   // Copy public key
   dst->n = BN_new();
   if (BN_copy(dst->n, src->n) != (dst->n)) { errprint("Could not copy pub->n"); return -1; }
   dst->e = BN_new();
   if (BN_copy(dst->e, src->e) != (dst->e)) { errprint("Could not copy pub->e"); return -1; }
   return 0;
}

int RSAPublicKey::ImportKeyFromASCII(const char *text, const char *name)
{
   if (key) RSA_free(key);
   int retval = 0;
   BIO *bo = BIO_new_mem_buf((void *)text, -1);
   EVP_PKEY *epkey = PEM_read_bio_PUBKEY(bo, NULL, 0, NULL);
   fSSLCheckError();
   if (!epkey)
   {
      retval = 1;
      errprint("could not import public key");
      key = NULL;
      goto bioshutdown;
   }
   key = EVP_PKEY_get1_RSA(epkey);
   if (key == NULL)
   {
      retval = -1;
      errprint("failed to get imported public key");
   }
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   EVP_PKEY_free(epkey);
   SetKeyName(name);
   return retval;
}

int RSAPublicKey::ImportKeyFromASCIIWithPassword(const char *text, const char *password, const char *name)
{
   errprint("password protection of RSA public keys is unsupported!");
   return ImportKeyFromASCII(text, name);
}

int RSAPublicKey::ExportKeyToASCII(char **data)
{
   return GetPEMKeyData(data);
}

int RSAPublicKey::ExportKeyToASCIIWithPassword(char **data, const char *password)
{
   errprint("password protection of RSA public keys is unsupported!");
   return GetPEMKeyData(data);
}
